/**
 * 
 */
package biz.innovasoft.ndb;

import java.io.Serializable;

import biz.innovasoft.ndb.index.IndexManager;
import biz.innovasoft.ndb.index.Searcher;
import biz.innovasoft.ndb.index.SearcherResult;
import biz.innovasoft.ndb.query.QueryCriteria;
import biz.innovasoft.ndb.query.Result;

/**
 * 
 * @author Diego Miranda
 *
 */
public class PreparedFindHelper implements Serializable {

	private static final long serialVersionUID = 1102956905193518896L;
	
	private GenericRepository repository;
	private Searcher searcher = new Searcher ();
	private IndexManager imanager;
	
	public PreparedFindHelper (GenericRepository repository, Class<?> queryClass) {
		this.repository = repository;
		imanager = repository.getIndexManager(queryClass);
		searcher.setIndexManager(imanager);
	}
	
	public Result find(QueryCriteria query, boolean copy) {
		
		Result result = new Result();
		result.setMaxResults(query.getMaxResults());
		result.setPage(query.getPage()+1);
		
		try {
			SearcherResult sresult = searcher.searchObject(query);
			if (sresult.size() > 0) {
				result.setTotalHits(sresult.getTotalHits());
				result.setMaxRange(sresult.getMaxRange());
				result.setMinRange(sresult.getMinRange());
				result.addAll(repository.getObjectsByOId(sresult.getOids(), copy));
				return result;
			}
		} catch (RuntimeException e) {
		}
			
		return result;
	}
	
}
